const app = getApp()

Page({
  data: {
    userList: [],
    loading: false,
    page: 1,
    hasMore: true,
    tabList: [
      { id: 'all', name: '全部用户' },
      { id: 'active', name: '活跃用户' },
      { id: 'new', name: '新增用户' },
      { id: 'vip', name: 'VIP用户' }
    ],
    activeTab: 'all'
  },

  onLoad() {
    this.loadUserList()
  },

  // 切换标签
  handleTabChange(e) {
    const { id } = e.currentTarget.dataset
    this.setData({
      activeTab: id,
      userList: [],
      page: 1,
      hasMore: true
    })
    this.loadUserList()
  },

  // 加载用户列表
  async loadUserList() {
    if (this.data.loading || !this.data.hasMore) return

    this.setData({ loading: true })

    // 模拟加载数据
    setTimeout(() => {
      const newUsers = [{
        id: 1,
        nickname: '张三',
        avatarUrl: '/images/default-avatar.png',
        phone: '138****8888',
        registerTime: '2024-01-29',
        lastLoginTime: '2024-01-29 12:00:00',
        orderCount: 5,
        totalSpent: 560.00,
        isVip: true
      }, {
        id: 2,
        nickname: '李四',
        avatarUrl: '/images/default-avatar.png',
        phone: '139****9999',
        registerTime: '2024-01-28',
        lastLoginTime: '2024-01-29 10:00:00',
        orderCount: 2,
        totalSpent: 220.00,
        isVip: false
      }]

      this.setData({
        userList: [...this.data.userList, ...newUsers],
        loading: false,
        page: this.data.page + 1,
        hasMore: this.data.page < 3
      })
    }, 500)
  },

  // 查看用户详情
  handleViewDetail(e) {
    const { id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/admin/user/detail?id=${id}`
    })
  },

  // 设置VIP状态
  handleToggleVip(e) {
    const { id, isVip } = e.currentTarget.dataset
    const actionText = isVip ? '取消' : '设为'

    wx.showModal({
      title: '提示',
      content: `确定要${actionText}该用户的VIP身份吗？`,
      success: (res) => {
        if (res.confirm) {
          // 更新用户VIP状态
          const userList = this.data.userList.map(item => {
            if (item.id === id) {
              return { ...item, isVip: !isVip }
            }
            return item
          })

          this.setData({ userList })

          wx.showToast({
            title: `${actionText}VIP成功`,
            icon: 'success'
          })
        }
      }
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      userList: [],
      page: 1,
      hasMore: true
    })
    this.loadUserList()
    wx.stopPullDownRefresh()
  },

  // 上拉加载更多
  onReachBottom() {
    this.loadUserList()
  }
}) 